package edu.sandau.app.basic.controller;

import edu.sandau.app.basic.domain.OrderDetail;
import edu.sandau.app.basic.domain.Order;
import edu.sandau.app.basic.domain.Cart;
import edu.sandau.app.basic.domain.DishWithBLOBs;
import edu.sandau.app.basic.golbal.GlobalEnum;
import edu.sandau.app.basic.service.OrderDetailService;
import edu.sandau.app.basic.service.OrderService;
import edu.sandau.app.basic.service.CartService;
import edu.sandau.app.basic.service.DishService;
import edu.sandau.app.basic.vo.BasicMsg;
import edu.sandau.app.basic.vo.BasicMsgWithData;
import edu.sandau.app.basic.vo.CreateOrderDetailRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/order-details")
@Tag(name = "订单详情管理", description = "订单详情管理接口")
public class OrderDetailController {
    
    @Autowired
    private OrderDetailService orderDetailService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private DishService dishService;
    
    // 根据订单ID获取订单详情
    @GetMapping("/order/{orderId}")
    @Operation(summary = "根据订单ID获取订单详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": [
                            {
                              "orderId": 1,
                              "dishId": 1,
                              "dishName": "宫保鸡丁",
                              "dishPrice": 28.00,
                              "quantity": 2,
                              "subtotal": 56.00
                            },
                            {
                              "orderId": 1,
                              "dishId": 2,
                              "dishName": "麻婆豆腐",
                              "dishPrice": 18.00,
                              "quantity": 1,
                              "subtotal": 18.00
                            }
                          ]
                        }"""),
                    @ExampleObject(name = "该订单暂无详情", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "该订单暂无详情",
                          "errorCode": "ORDER_NOT_FOUND",
                          "data": null
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "ORDER_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<List<OrderDetail>> getOrderDetailsByOrderId(@PathVariable Long orderId) {
        BasicMsgWithData<List<OrderDetail>> msg = new BasicMsgWithData<>();
        try {
            List<OrderDetail> orderDetails = orderDetailService.getOrderDetailsByOrderId(orderId);
            msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
            msg.setErrorMsg("查询成功");
            msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            msg.setData(orderDetails);
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 根据ID获取订单详情
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取订单详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": {
                            "detailId": 1,
                            "orderId": 1,
                            "dishId": 1,
                            "dishName": "宫保鸡丁",
                            "dishPrice": 28.00,
                            "quantity": 2,
                            "subtotal": 56.00
                          }
                        }"""),
                    @ExampleObject(name = "订单详情不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单详情不存在",
                          "errorCode": "ORDER_NOT_FOUND",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<OrderDetail> getOrderDetailById(@PathVariable Long id) {
        BasicMsgWithData<OrderDetail> msg = new BasicMsgWithData<>();
        try {
            OrderDetail orderDetail = orderDetailService.getOrderDetailById(id);
            if (orderDetail != null) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("查询成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
                msg.setData(orderDetail);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_NOT_FOUND);
                msg.setErrorMsg("订单详情不存在");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 创建订单详情
    @PostMapping
    @Operation(summary = "创建订单详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "创建成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "订单详情创建成功，总金额：68.00",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "订单ID不能为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单ID不能为空",
                          "errorCode": "ORDER_DETAIL_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "订单不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单不存在",
                          "errorCode": "ORDER_DETAIL_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "购物车为空", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单对应的用户购物车为空，无法创建订单详情",
                          "errorCode": "ORDER_DETAIL_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "菜品不存在", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "购物车中存在已下架的菜品，无法创建订单详情",
                          "errorCode": "ORDER_DETAIL_CREATE_FAIL"
                        }"""),
                    @ExampleObject(name = "创建失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单详情创建失败: 具体错误信息",
                          "errorCode": "ORDER_DETAIL_CREATE_FAIL"
                        }""")
                }))
    })
    public BasicMsg addOrderDetail(@RequestBody CreateOrderDetailRequest request) {
        BasicMsg msg = new BasicMsg();
        try {
            // 验证订单ID
            if (request.getOrderId() == null) {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DETAIL_CREATE_FAIL);
                msg.setErrorMsg("订单ID不能为空");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 验证订单是否存在
            Order order = orderService.getOrderById(request.getOrderId());
            if (order == null) {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DETAIL_CREATE_FAIL);
                msg.setErrorMsg("订单不存在");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 获取用户购物车商品
            List<Cart> cartItems = cartService.getUserCart(order.getUserId());
            if (cartItems == null || cartItems.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DETAIL_CREATE_FAIL);
                msg.setErrorMsg("订单对应的用户购物车为空，无法创建订单详情");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                return msg;
            }
            
            // 为每个购物车商品创建订单详情
            int totalCreated = 0;
            BigDecimal totalAmount = BigDecimal.ZERO;
            
            for (Cart cartItem : cartItems) {
                // 从菜品表获取菜品信息
                DishWithBLOBs dish = dishService.getDishById(cartItem.getDishId());
                if (dish == null || !"0".equals(dish.getDishStatus())) {
                    // 如果菜品不存在或已下架，跳过该商品
                    continue;
                }
                
                // 创建订单详情对象
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(request.getOrderId());
                orderDetail.setDishId(cartItem.getDishId());
                orderDetail.setDishName(dish.getDishName());
                orderDetail.setDishPrice(dish.getDishPrice());
                orderDetail.setQuantity(cartItem.getQuantity());
                
                // 计算小计：数量 × 单价
                BigDecimal itemSubtotal = dish.getDishPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity()));
                orderDetail.setSubtotal(itemSubtotal);
                
                // 累加总金额
                totalAmount = totalAmount.add(itemSubtotal);
                
                // 保存订单详情
                int result = orderDetailService.addOrderDetail(orderDetail);
                if (result > 0) {
                    totalCreated++;
                }
            }
            
            if (totalCreated > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("订单详情创建成功，总金额：" + totalAmount);
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DETAIL_CREATE_FAIL);
                msg.setErrorMsg("订单详情创建失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DETAIL_CREATE_FAIL);
            msg.setErrorMsg("订单详情创建失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 删除订单详情
    @DeleteMapping("/{id}")
    @Operation(summary = "删除订单详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作完成",
            content = @Content(mediaType = "application/json",
                examples = {
                    @ExampleObject(name = "删除成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "订单详情删除成功",
                          "errorCode": "Ok"
                        }"""),
                    @ExampleObject(name = "删除失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单详情删除失败",
                          "errorCode": "ORDER_DELETE_FAIL"
                        }"""),
                    @ExampleObject(name = "系统错误", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "订单详情删除失败: 具体错误信息",
                          "errorCode": "ORDER_DELETE_FAIL"
                        }""")
                }))
    })
    public BasicMsg deleteOrderDetail(@PathVariable Long id) {
        BasicMsg msg = new BasicMsg();
        try {
            int result = orderDetailService.deleteOrderDetail(id);
            if (result > 0) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("订单详情删除成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DELETE_FAIL);
                msg.setErrorMsg("订单详情删除失败");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_DELETE_FAIL);
            msg.setErrorMsg("订单详情删除失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
        }
        return msg;
    }
    
    // 根据菜品ID获取订单详情
    @GetMapping("/dish/{dishId}")
    @Operation(summary = "根据菜品ID获取订单详情")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "操作成功",
            content = @Content(mediaType = "application/json", 
                examples = {
                    @ExampleObject(name = "查询成功", value = """
                        {
                          "operateResult": "SUCC",
                          "errorMsg": "查询成功",
                          "errorCode": "Ok",
                          "data": [
                            {
                              "orderId": 1,
                              "dishId": 1,
                              "dishName": "宫保鸡丁",
                              "dishPrice": 28.00,
                              "quantity": 2,
                              "subtotal": 56.00
                            },
                            {
                              "orderId": 2,
                              "dishId": 1,
                              "dishName": "宫保鸡丁",
                              "dishPrice": 28.00,
                              "quantity": 1,
                              "subtotal": 28.00
                            }
                          ]
                        }"""),
                    @ExampleObject(name = "该菜品暂无订单详情", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "该菜品暂无订单详情",
                          "errorCode": "ORDER_NOT_FOUND",
                          "data": null
                        }"""),
                    @ExampleObject(name = "查询失败", value = """
                        {
                          "operateResult": "UNSUSS",
                          "errorMsg": "查询失败: 数据库连接异常",
                          "errorCode": "ORDER_QUERY_FAIL",
                          "data": null
                        }""")
                }))
    })
    public BasicMsgWithData<List<OrderDetail>> getOrderDetailsByDishId(@PathVariable Long dishId) {
        BasicMsgWithData<List<OrderDetail>> msg = new BasicMsgWithData<>();
        try {
            List<OrderDetail> orderDetails = orderDetailService.getOrderDetailsByDishId(dishId);
            if (orderDetails != null && !orderDetails.isEmpty()) {
                msg.setErrorCode(GlobalEnum.ErrorCode.Ok);
                msg.setErrorMsg("查询成功");
                msg.setOperateResult(GlobalEnum.OperateResult.SUCC);
                msg.setData(orderDetails);
            } else {
                msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_NOT_FOUND);
                msg.setErrorMsg("该菜品暂无订单详情");
                msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
                msg.setData(null);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.ORDER_QUERY_FAIL);
            msg.setErrorMsg("查询失败: " + e.getMessage());
            msg.setOperateResult(GlobalEnum.OperateResult.UNSUSS);
            msg.setData(null);
        }
        return msg;
    }
}
